package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.manager.mapper.SysRoleUserMapper;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.AssginRoleDto;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    // 用户登录
    @Override
    public LoginVo login(LoginDto loginDto) {

        // 校验验证码是否正确
        String captcha = loginDto.getCaptcha();
        String codeKey = loginDto.getCodeKey();

        // 从redis里面获取验证码
        String redisCode = redisTemplate.opsForValue().get("user:validate" + codeKey);

        // 比较redis里面的验证码是否为空 和 输入的验证码和redis存储的验证码是否一致
        if (StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode, captcha)) {
            throw  new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        // 验证码通过 删除redis中的验证码
        redisTemplate.delete("user:validate" + codeKey);

        // 1.获取提交用户名，LoginDto获取到
        String userName = loginDto.getUserName();

        // 2.根据用户查询数据库 sys_user表
        SysUser sysUser = sysUserMapper.selectByUserName(userName);

        // 3.如果根据用户名查不到对应的信息，用户名不存在，返回错误信息
        if (sysUser == null) {
//            throw  new RuntimeException("用户名不存在");
               throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 4.如果根据用户名查询到用户信息，用户存在
        // 5.获取输入的密码, 比较输入的密码和数据库密码是否一致
        String database_password = sysUser.getPassword(); // 数据库存的密码
        // 把输入的密码进行加密操作 再跟数据库里的加密密码进行对比
        String input_password =
                DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());

        // 6. 如果密码一致，登录成功，如果密码不一致登录失败
        if (!input_password.equals(database_password)) {
//            throw new RuntimeException("密码不正确");
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }

        // 7.登录成功，生成唯一标识token
        String token = UUID.randomUUID().toString().replaceAll("-", "");

        // 8.把登录成功用户信息放到redis里面
        // key: token value: 用户信息
        redisTemplate.opsForValue()
                .set("user:login" + token,
                        JSON.toJSONString(sysUser),
                        7,
                        TimeUnit.DAYS);

        // 9.返回loginVo对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;

    }

    @Override
    public SysUser getUserInfo(String token) {
        // 根据token来获取用户的信息
        String userJson = redisTemplate.opsForValue().get("user:login" + token);
        return JSON.parseObject(userJson, SysUser.class);
    }

    @Override
    public void logout(String token) {
        // 后端根据token从Redis中删除用户数据
        redisTemplate.delete("user:login" + token);
    }

    @Override
    public PageInfo<SysUser> findBypage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
       List<SysUser> sysUserList = sysUserMapper.findByPage(sysUserDto);
       PageInfo<SysUser> pageInfo = new PageInfo<>(sysUserList);
       return pageInfo;
    }

    @Override
    public void saveSysUser(SysUser sysUser) {
        // 根据输入的用户名去查找用户
        SysUser dbSysUser = sysUserMapper.selectByUserName(sysUser.getUserName());
        if (dbSysUser != null) {
            throw  new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        String password = sysUser.getPassword();
        String digestPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(digestPassword);

        // 设置status的状态
        sysUser.setStatus(1);
        sysUserMapper.saveSysUser(sysUser);
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser);
    }

    @Override
    public void deleteById(Long userId) {
        sysUserMapper.deleteById(userId);
    }

    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        // 根据userId删除用户之前分配角色数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId());

        // 重新分配数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        for(Long roleId : roleIdList) {
            sysRoleUserMapper.doAssign(assginRoleDto.getUserId(), roleId);
        }

    }
}
